package vn.edu.hut.soict.translate.dictionary.bilingual;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class BilingualDictionaryReader {
	private static final String SYNOMYM_DIRECTION = "(cũng viết:";

	private BilingualDictionary dictionary;

	public BilingualDictionaryReader() {

	}

	public BilingualDictionary read(String file) {
		dictionary = new BilingualDictionary();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				int separatorIndex = line.indexOf(':');
				String entry = line.substring(0, separatorIndex).trim();
				String contents = line.substring(separatorIndex + 1, line.length()).trim();
				if (contents.startsWith(SYNOMYM_DIRECTION)) {
					handleSynonym(entry, contents);
				}
				else {
					handleNormal(entry, contents);
				}
			}
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				if (reader != null) {
					reader.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}

		return dictionary;
	}

	private void handleNormal(String entry, String contents) {
		String[] contentList = removeComment(contents).split(",");
		for (String content : contentList) {
			dictionary.addEntry(entry, content.trim());
		}
	}

	private void handleSynonym(String entry, String contents) {
		String synonyms = contents.substring(SYNOMYM_DIRECTION.length(), contents.indexOf(')'));
		String[] synonymList = synonyms.split(",");
		String[] contentList = removeComment(contents).split(",");
		for (String content : contentList) {
			dictionary.addEntry(entry, content.trim());
			for (String synonym : synonymList) {
				dictionary.addEntry(synonym.trim(), content.trim());
			}
		}

	}

	private String removeComment(String content) {
		while (true) {
			int first = content.indexOf('(');
			if (first < 0) {
				break;
			}
			int last = content.indexOf(')');
			if (last >= 0) {
				content = content.substring(0, first) + content.substring(last + 1, content.length());
			}
		}
		return content.trim();
	}
}